import React, { FC, useEffect, useState } from 'react'
import { addFunction, deleteFunction, detailFunction, updateFunction } from '@/services/function'
import { Button, Form, Input, message, Modal, Radio } from 'antd'
import FunRetType from '@pages/ControllerView/components/FunctionConfig/FunRetType'
import FunReqArg from '@pages/ControllerView/components/FunctionConfig/FunReqArg'
const confirm = Modal.confirm
const FormItem = Form.Item
const formTailLayout = {
  labelCol: { span: 5 },
  wrapperCol: { span: 11 }
}
const tailLayout = {
  wrapperCol: { offset: 5, span: 10 }
}

interface DetailFunctionFormProps {
  funId:string,
  projectId:string,
  again:any,
  fileId:string,
}

const DetailFunctionForm: FC<DetailFunctionFormProps> = (props) => {

  const [form] = Form.useForm()

  const [funDetail, setFunDetail] = useState<any>({})

  // 方法返回类型
  const [returnShow, setReturnShow] = useState<string>(' ')
  const [retVisible, setRetVisible] = useState<boolean>(false)
  const changeRetVisible = (flag: boolean) => {
    setRetVisible(flag)
    if (!flag) getDetail();
  }

  // 设置请求参数
  const [parVis,setParVis] = useState<boolean>(false);
  const [returnPar, setReturnPar] = useState<string>(' ')

  const changeParVis = (flag:boolean) => {
    setParVis(flag);
    if (!flag) getDetail();
  }

  const { funId,projectId,again,fileId } = props

  useEffect(() => {
    if (funId !== '0') {
      getDetail();
    }
  }, [funId])

  const getDetail = () => {
    detailFunction({ id: funId }).then(res => {
      if (res.code === 10000) {
        setFunDetail(res.data)
        setReturnShow(res.data.return_show || ' ')
        const arg = eval(res.data.arg || []);
        const showArr:any[] = [];
        arg.forEach((value:any) => {
          showArr.push(value.arg_type_name + ' ' + value.name);
        })

        const argShow = '(' + showArr.join(', ') + ')';
        setReturnPar(argShow || ' ')
        form.resetFields()
      }
    })
  }

  const delFunction = async () => {

    confirm({
      title: '删除此方法?',
      content: '请确认是否删除？',
      okText: '是',
      okType: 'danger',
      cancelText: '否',
      onOk() {
        if (funId == '0') {
          again();
          message.success('删除成功！')
          return ;
        }
        deleteFunction({ id: funDetail.id }).then(res => {
          if (res.code === 10000) {
            message.success('删除成功！')
            again();
          }
        })
      },
    })
  }

  const handleOk = async () => {
    const { validateFields } = form
    const values = await validateFields()

    values.cid = fileId;
    if (funId == '0') {
      addFunction(values).then(res => {
        if (res.code === 10000) {
          message.success('添加成功！')
          again();
        }
      })
    }else {
    values.id = funId
    // 提交数据
    updateFunction(values).then(res => {
      if (res.code === 10000) {
        message.success('保存成功！')
        again();
      }
    })
    }
  }

  return (
    <>
      <Form form={form} initialValues={funDetail} onFinish={() => handleOk()}>
        <FormItem {...formTailLayout} name="name" rules={[{ required: true, message: '请输入方法中文名称' }]} label="中文名称">
          <Input placeholder="请输入方法中文名称"/>
        </FormItem>
        <FormItem {...formTailLayout} name="comment" rules={[{ required: true, message: '请输入方法注释' }]} label="方法注释">
          <Input placeholder="请输入方法注释"/>
        </FormItem>
        <FormItem {...formTailLayout} name="req_path" rules={[{ required: true, message: '请输入方法请求地址' }]} label="请求地址">
          <Input placeholder="请输入方法请求地址"/>
        </FormItem>
        <FormItem {...formTailLayout} name="req_method" rules={[{ required: true, message: '请选择请求方式' }]} label="请求方式">
          <Radio.Group>
            <Radio.Button value="GET">GET</Radio.Button>
            <Radio.Button value="POST">POST</Radio.Button>
            <Radio.Button value="PUT">PUT</Radio.Button>
            <Radio.Button value="DELETE">DELETE</Radio.Button>
            <Radio.Button value="HEAD">HEAD</Radio.Button>
            <Radio.Button value="TRACE">TRACE</Radio.Button>
            <Radio.Button value="OPTIONS">OPTIONS</Radio.Button>
          </Radio.Group>
        </FormItem>
        <FormItem {...formTailLayout} name="fun_name" rules={[{ required: true, message: '请输入方法英文名称' }]} label="英文名称">
          <Input placeholder="请输入方法英文名称"/>
        </FormItem>
        <FormItem {...formTailLayout} label="返回类型">
          <Button style={{ width: '100%' }} onClick={() => {
            if (funDetail.id) {
              changeRetVisible(true)
            }else {
              form.validateFields().then(res => {
                message.warn('请先保存方法！')
              })
            }
          }}>{returnShow || ' '}</Button>
        </FormItem>
        <FormItem {...formTailLayout}  label="请求参数">
          <Button style={{ width: '100%' }} onClick={() => {
            if (funDetail.id) {
              changeParVis(true)
            }else {
              form.validateFields().then(res => {
                message.warn('请先保存方法！')
              })
            }
          }}>{returnPar || ' '}</Button>
        </FormItem>
        <FormItem {...tailLayout}>
          <Button type="primary" htmlType="submit">保存</Button>
          <Button onClick={delFunction} style={{ marginLeft: 8 }}>删除</Button>
        </FormItem>
      </Form>
      {/* 方法返回参数 */}
      <FunRetType projectId={projectId} funDetail={funDetail} onClose={changeRetVisible} visible={retVisible} />
      {/* 方法请求参数 */}
      <FunReqArg projectId={projectId} onClose={changeParVis} visible={parVis} funId={funDetail.id} />
    </>
  )
}

export default DetailFunctionForm
